package local.app.server_audits;

import com.jcraft.jsch.*;
import local.app.authentiction.AuthenticationRSA;
import local.app.servers.Server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;

public class ServerChecker {
    public final int pingTimeout = 7000;
    private Server server;
    //private Session session;

//    public ServerChecker(Server server) {
//        this.server = server;
//        try {
//            if (this.server instanceof AuthenticationRSA) {
//
//                this.session = this.server.setConfigAndReturnSession(AuthenticationRSA.userName,
//                        AuthenticationRSA.pathToPrivateKey, AuthenticationRSA.password);
//
//            } else  {
//
//                this.session = this.server.setConfigAndReturnSession();
//            }
//        } catch (JSchException e) {
//            System.out.println("Возникла ошибка: " + e);
//        }
//    }

    public ServerChecker(Server server) {
        this.server = server;
    }

    public boolean pingServer() {
        try {
            InetAddress host = InetAddress.getByName(server.getIpAddress());
            return host.isReachable(pingTimeout);
        } catch (Exception e) {
            System.out.println("Возникла ошибка: " + e);
            return false;
        }

    }

    public boolean authenticateSSH() {
        try {
            //Session session = server.setConfigAndReturnSession();
            server.session.connect();
            return server.session.isConnected();
        } catch (Exception e) {
            return false;
        }
    }

    public String getOSVersion() {
        try {
            String line = "";
            BufferedReader reader;
            ChannelExec channel = (ChannelExec) server.session.openChannel("exec");

            channel.setCommand("uname -a");
            channel.connect();

            reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            line += reader.readLine() + "\n";

            channel.disconnect();

            ChannelExec channel1 = (ChannelExec) server.session.openChannel("exec");


            channel1.setCommand("cat /proc/version");
            channel1.connect();

            reader = new BufferedReader(new InputStreamReader(channel1.getInputStream()));
            line += reader.readLine() + "\n";

            channel1.disconnect();
            server.session.disconnect();

            return line;
        } catch (Exception e) {
            return "Unknown";
        }
    }
}
